package com.office.reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;

import com.office.AbstractReader;

public class WordReader extends AbstractReader {
	
	public static String readWord(String filePath,String imgSavePath) {
		if (filePath.endsWith("doc") || filePath.endsWith("DOC")) {
			return readWord2003(filePath,imgSavePath);
		} else if (filePath.endsWith("docx") || filePath.endsWith("DOCX")) {
			return readWord2007(filePath,imgSavePath);
		} else {
			return "";
		}
	}


	public static String readWord2003(String filePath, String imgSavePath) {
		
		String text = "";
		try {
			FileInputStream in = new FileInputStream(new File(filePath));
			HWPFDocument doc = new HWPFDocument(in);
			int length = doc.characterLength();
			PicturesTable pTable = doc.getPicturesTable();
			text = doc.getDocumentText();

			System.out.println(text);

			for (int i = 0; i < length; i++) {
				Range range = new Range(i, i + 1, doc);
				CharacterRun cr = range.getCharacterRun(0);
				if (pTable.hasPicture(cr)) {
					Picture pic = pTable.extractPicture(cr, false);
					String afileName = pic.suggestFullFileName();
					OutputStream out = new FileOutputStream(new File(
							imgSavePath + UUID.randomUUID() + afileName));
					pic.writeImageContent(out);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return text;
	}


	@SuppressWarnings("resource")
	public static String readWord2007(String filePath, String imgSavePath) {
		
		File file = new File(filePath);
		String text = "";
		try {
			FileInputStream fis = new FileInputStream(file);
			XWPFDocument document = new XWPFDocument(fis);
			XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(
					document);
			text = xwpfWordExtractor.getText();
			System.out.println(text);
			List<XWPFPictureData> picList = document.getAllPictures();
			for (XWPFPictureData pic : picList) {
				byte[] bytev = pic.getData();
				FileOutputStream fos = new FileOutputStream(imgSavePath
						+ pic.getFileName());
				fos.write(bytev);
			}
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return text;
	}

}